package com.bw.mvi.mvi

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.launch

/**
 * viewModel:接受意图(Channel通道)--》根据不同意图发起网络请求----》获取数据--》更新State
 */
class PostsViewModel:ViewModel() {

    val intents = Channel<PostsIntent>(Channel.UNLIMITED) //通过
    private val repository:PostRepository by lazy {
        PostRepository()
    }
    private val postsFlow:MutableStateFlow<PostsState>  by  lazy {
        MutableStateFlow(PostsState.Loading)
    }
    val  postsFlow_:StateFlow<PostsState> = postsFlow

    init {
        //2:处理意图
        handleIntent()
    }
    //2：接受意图(Channel通道)--》根据不同意图发起网络请求-
    private fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect{
                when(it){
                    is PostsIntent.LoadPosts -> getPostList(it.pageNum,it.pageSize)
                }
            }
        }

    }
    //3：获取数据--》更新State
    private fun getPostList(pageNum: Int, pageSize: Int) {
        viewModelScope.launch {
            repository.getPostList(pageNum,pageSize)
                .catch {
                    postsFlow.value = PostsState.Error(it.message.toString())
                }
                .filter {
                    it?.data != null
                }
                .collect{
                    //更新State
                    if (it.code != 200){
                        postsFlow.value = PostsState.Error(it.message)
                    }else{
                        if (it.data.size == 0){
                            postsFlow.value = PostsState.Empty
                        }else{
                            postsFlow.value = PostsState.Success(it.data)
                        }
                    }
            }
        }
    }


}